package com.veetao.api.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.veetao.api.service.PassportService;
import com.veetao.api.utils.McpUtils;
import com.veetao.api.utils.Md5Utils;
import com.veetao.api.utils.NumberUtil;

@Service("passportService")
public class PassportServiceImpl implements PassportService {

	@Value("${passport.salt}")
	private String passportSalt;
	
	public PassportServiceImpl() {
		super();
	}

	@Override
	public boolean checkTicket(int userId, String ticket) {
		String[] ticketComponents = ticket.split("\\|");
		if(ticketComponents.length != 3) {
			return false;
		}
		String ts = ticketComponents[2];
		return ticket.equals(generateTicket(userId, ts));
	}
	
	@Override
	public int checkTicket(String ticket) {
		String[] ticketComponents = ticket.split("\\|");
		if(ticketComponents.length != 3) {
			return -1;
		}
		String userIdStr = ticketComponents[0];
		if(!NumberUtil.isNumber(userIdStr)) {
			return -1;
		}
		String ts = ticketComponents[2];
		int userId = Integer.parseInt(userIdStr);
		if(ticket.equals(generateTicket(userId, ts))) {
			return userId;
		}
		
		return -1;
	}
	
	private String tokenTemplate = "%s|%s|%s";
	@Override
	public String generateTicket(int userId) {
		long ts = System.currentTimeMillis();
		return generateTicket(userId, ts+"");
	}
	
	
	private String generateTicket(int userId, String timeStr) {
//		String salt = "com.b#e$r%k_)gen";
		String md5 = Md5Utils.md5(userId + passportSalt + timeStr);
		
		String t = String.format(tokenTemplate, userId,md5,timeStr);
		
		return t;
		
	}
	
	public static void main(String[] args) {
		PassportServiceImpl service = new PassportServiceImpl();
		service.passportSalt = "t#an&q#ian%s";
		int uid = 56;
//		String md5 = Md5Utils.md5("wx_biz_publickey" + service.passportSalt + System.currentTimeMillis());
//		System.out.println(md5);
		System.out.println("t=" + service.generateTicket(uid));
		System.out.println("uid=" + uid);
		
		System.out.println(Md5Utils.md5("wxpay_s_" + System.currentTimeMillis() + service.passportSalt));
		String s = McpUtils.aesEncode("wxpay_s_" + System.currentTimeMillis(), service.passportSalt);
		System.out.println(s.length());
	}

	public String getPassportSalt() {
		return passportSalt;
	}

	public void setPassportSalt(String passportSalt) {
		this.passportSalt = passportSalt;
	}



}
